﻿using System;
using System.Web.UI;
using Telerik.Web.UI;
using ImageGallery.DAL;
using System.IO;
using Telerik.Web.UI.ImageEditor;

public partial class UploadPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Page.Master.FindControl("buttonUploadPhotos").Visible = false;
        }
    }

    protected void ButtonUploadImages_Click(object sender, EventArgs e)
    {
        foreach (UploadedFile file in asyncUploadImages.UploadedFiles)
        {
            Photo photo = new Photo();

            photo.Data = GetResizedPhoto(file.InputStream);

            string title = file.GetFieldValue("Title");
            string location = file.GetFieldValue("Location");
            string description = file.GetFieldValue("Description");

			photo.Title = (title.Length > 150) ? title.Substring(0, 150) : title;
			photo.Location = (location.Length > 150) ? location.Substring(0, 150) : location;
			photo.Description = (description.Length > 600) ? description.Substring(0, 600) : description;
			photo.Rating = 0;
			photo.RatesCount = 0;
            PhotoDAO.InsertPhoto(photo);
        }

        labelSuccessMessage.Text = "You have successfully uploaded the photos! In <span id='redirectCounter'>10</span> seconds you will be redirected to the home page.";
        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "redirectScript", "Sys.Application.add_load(successRedirect);", true);
    }

    private byte[] GetResizedPhoto(Stream stream)
    {
        byte[] result = null;
        int maxSize = 640; //the maximum dimensions for the image

        //An EditableImage object from the RadImageEditor's API
        //it is used to facilitate resizing and provide cross-format compatibility
        EditableImage ei = new EditableImage(stream);
        using (ei)
        {
            int currWidth = ei.Width, currHeight = ei.Height;
            //the aspect ratio of the image. Used for calculating the new size
            float aspectRatio = (float)currWidth / currHeight;

            if (currWidth > maxSize || currHeight > maxSize)
            {
                if (currWidth > currHeight)
                {
                    currWidth = maxSize;
                    currHeight = (int)Math.Round((double)(currWidth / aspectRatio));
                }
                else
                {
                    currHeight = maxSize;
                    currWidth = (int)Math.Round((double)(aspectRatio * currHeight));
                }
                ei.Resize(currWidth, currHeight);
            }
            MemoryStream ms = new MemoryStream();
            using (ms)
            {
                ei.Image.Save(ms, ei.RawFormat);
                result = ms.ToArray();
            }
        }
        return result;
    }
}
